import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:usbflutter/usb/UsbManager.dart';
import 'package:usbflutter/usb/UsbPackage.dart';
import 'package:usbflutter/usb/UsbResult.dart';

class ConnectPage extends StatefulWidget {
  final int deviceId;

  const ConnectPage(this.deviceId, {super.key});

  @override
  State<StatefulWidget> createState() {
    return _ConnectPageState();
  }
}

class _ConnectPageState extends State<ConnectPage> {
  String text = '';

  UsbResult? usbResult;

  @override
  void initState() {
    super.initState();
    _connect();
    UsbManager.instance.subscribe(widget.deviceId, _onNewData);
  }

  @override
  void dispose() {
    UsbManager.instance.unsubscribe(widget.deviceId, _onNewData);
    UsbManager.instance.disconnect(widget.deviceId);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    UsbResult? result = usbResult;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme
            .of(context)
            .colorScheme
            .inversePrimary,
        title: const Text("连接设备"),
      ),
      body: Column(
        children: [
          const SizedBox(
            height: 100,
          ),
          if (result == null || result.code != 0)
            Container(
              alignment: Alignment.center,
              child: Text(
                result == null ? '连接中..' : '失败: ${result.msg}',
                style: const TextStyle(fontSize: 24),
              ),
            ),
          if (result != null && result.code == 0)
            Container(
              alignment: Alignment.center,
              child: Text(
                text,
                style: const TextStyle(fontSize: 24),
              ),
            )
        ],
      ),
    );
  }

  Future<void> _connect() async {
    usbResult = await UsbManager.instance.connect(widget.deviceId);
    setState(() {});
  }

  /// 数据更新
  void _onNewData(UsbPackage data) {
    if (data.event == UsbPackage.NEW_DATA) {
      text = data.handler?.toString() ?? '';
      usbResult = UsbResult(0, '已连接');
      setState(() {});
      return;
    }
    if (data.event == UsbPackage.USB_PERMISSION) {
      _connect();
      return;
    }
    usbResult = UsbResult(-1, '设备已断开');
    setState(() {});
  }
}